<template>
    <div>
        <!-- 门票列表区域 -->
        <div v-show="activeStatu">
            <el-card class="box">
                <!-- 搜索筛选区域 -->
                <div style="padding: 10px">
                    <div class="flex">
                        <div style="width: 220px">门票名称</div>
                        <div class="time_top">上架/下架</div>
                    </div>
                    
                    <!-- 搜索框和筛选器 -->
                    <div class="flexBox">
                        <div> 
                            <el-input v-model.trim="inputed" @input="filters" placeholder="输入内容" style="width: 220px">
                                <template #prefix>
                                    <el-icon class="el-input__icon">
                                        <search />
                                    </el-icon>
                                </template>
                            </el-input>
                        </div>
                        <div style="margin-left: 20px;">
                            <el-select v-model="value" @change="ange_indexof" clearable placeholder="请选择"
                                style="width: 240px">
                                <el-option v-for="item in options" :label="item.label" :value="item.value" />
                            </el-select>
                        </div>
                    </div>
                    
                    <!-- 操作按钮 -->
                    <div style="display: flex;">
                        <div><el-button type="primary" @click="add" class="add_class">新增</el-button></div>
                        <el-button type="danger" class="delelist" @click="deleList">批量删除</el-button>
                    </div>
                    
                    <!-- 门票列表表格 -->
                    <div>
                        <el-table :data="activeList.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
                            style="margin-top: 10px;width: 100%;" :cell-style="{ 'text-align': 'center' }" lazy="true"
                            height="auto" v-el-table-infinite-scroll="handleTableScroll"
                            :header-cell-style="{ 'text-align': 'center' }" @selection-change="handleSelectionChange">
                            <el-table-column type="selection" fixed="left" />
                            <el-table-column prop="id" label="序号" fixed="left" />
                            <el-table-column prop="title" label="门票名称" show-overflow-tooltip />
                            
                            <!-- 门票状态开关 -->
                            <el-table-column prop="" label="门票状态">
                                <template #default="scope">
                                    <div class="handle">
                                        <el-switch @change="funstatus(scope.row)"
                                            :model-value="scope.row.state == 1 ? true : scope.row.state == 2 ? false : scope.row.state"
                                            inline-prompt />
                                    </div>
                                </template>
                            </el-table-column>
                            
                            <el-table-column prop="price" label="门票价格" sortable show-overflow-tooltip />
                            <el-table-column prop="intr" label="门票简介" show-overflow-tooltip />
                            <el-table-column prop="sold" sortable label="销量" />
                            <el-table-column prop="createtime" show-overflow-tooltip label="创建时间" />
                            
                            <!-- 操作列 -->
                            <el-table-column label="操作" width="250" fixed="right">
                                <template #default="scope">
                                    <div class="handle">
                                        <div @click="edit(scope.row)"
                                            style="color: rgba(64, 158, 255, 1);cursor: pointer">编辑</div>
                                        <div style="width: 10px;"></div>
                                        <div @click="deletes(scope.row)" style="color: red; cursor: pointer;">删除</div>
                                    </div>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>

                    <!-- 分页控件 -->
                    <div class="paging">
                        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                            :page-sizes="[5, 10, 20, 50]" :small="small" :disabled="disabled" background
                            layout="total, sizes, prev, pager, next, jumper" :total="activeList.length" />
                    </div>
                    
                    <!-- 删除确认弹窗 -->
                    <el-dialog title="删除" v-model="centerDialogVisible" width="30%" center>
                        <div style="font-size: 16px; padding-bottom: 20px">确认删除该门票吗?</div>
                        <div style="display: flex; justify-content: end">
                            <el-button @click="centerDialogVisible = false">取 消</el-button>
                            <el-button type="primary" @click="deleteid">确 定</el-button>
                        </div>
                    </el-dialog>
                </div>
                
                <!-- 批量删除确认弹窗 -->
                <el-dialog v-model="shows" title="是否要删除" center width="20vw">
                    <el-button @click="shows = false">取 消</el-button>
                    <el-button type="primary" @click="oks">确 定</el-button>
                </el-dialog>
                
                <!-- 批量删除确认弹窗 -->
                <el-dialog title="批量删除" v-model="centerDialogVisiblet" width="30%" center>
                    <div style="font-size: 16px">确认删除这批数据吗?</div>
                    <span slot="footer" style="display: flex; justify-content: space-between" class="dialog-footer">
                        <div></div>
                        <div>
                            <el-button @click="centerDialogVisiblet = false">取 消</el-button>
                            <el-button type="primary" @click="deleteid_t">确 定</el-button>
                        </div>
                    </span>
                </el-dialog>
            </el-card>
        </div>
        
        <!-- 新增/编辑门票表单区域 -->
        <div v-show="activeStatud" style="padding: 10px">
            <el-card style="width: 96%;margin-left: 2%;margin-top: 1%;position: relative;height: auto;">
                <div style="padding: 10px">{{ title }}</div>
                <div style="width: 100%;height: 1px; background-color: rgba(195, 195, 195, 1);"></div>
                
                <!-- 表单区域 -->
                <div style="margin-top: 50px;margin-left: 100px;">
                    <el-form ref="ruleFormRef" style="width:90%" :model="ruleForm" status-icon :rules="rules"
                        label-position="left" label-width="auto" class="demo-ruleForm">
                        <div style="display: flex;width: 100%;justify-content: space-between;">
                            <div style="width: 48%;">
                                <!-- 景区选择 -->
                                <el-form-item label="景区选择" prop="name" style="width: 90%">
                                    <el-select v-model="ruleForm.name" @change="ange_indexof" clearable
                                        placeholder="请选择" style="width: 90%">
                                        <el-option v-for="item in sceniclist" :label="item.title" :value="item.id" />
                                    </el-select>
                                </el-form-item>
                                
                                <!-- 门票名称 -->
                                <el-form-item label="门票名称" prop="title" style="width: 90%">
                                    <el-input v-model.trim="ruleForm.title" placeholder="请输入" style="width: 90%" />
                                </el-form-item>
                                
                                <!-- 门票价格输入框 -->
                                <el-form-item label="门票价格" prop="price" style="width: 90%">
                                    <div class="custom-number-input">
                                        <button type="button" @click="decreaseQuantity">-</button>
                                        <input type="text" v-model="ruleForm.price" @input="handleQuantityInput"
                                            @blur="validateQuantityInput" />
                                        <button type="button" @click="increaseQuantity">+</button>
                                    </div>
                                </el-form-item>
                                
                                <!-- 上下架开关 -->
                                <el-form-item prop="switch" label="上下架">
                                    <el-switch @change="funstate()" v-model="ruleForm.switch" />
                                </el-form-item>
                            </div>
                            
                            <!-- 门票简介 -->
                            <div style="width: 48%;">
                                <el-form-item label="门票简介" prop="synopsis" style="width: 90%">
                                    <el-input v-model.trim="ruleForm.synopsis" maxlength="220" style="width: 90%"
                                        placeholder="年龄12周岁(含)以上" show-word-limit type="textarea"
                                        :autosize="{ minRows: 3, maxRows: 5 }" />
                                </el-form-item>
                            </div>
                        </div>
                        <div style="height: 130px;"></div>
                        <div style="height: 30px;"></div>
                    </el-form>
                    
                    <!-- 表单底部按钮 -->
                    <div class="dialog-footer" style="position: absolute;bottom: 10px;right: 40px;">
                        <el-button type="primary" @click="submitForm(ruleFormRef)">确认</el-button>
                        <el-button @click="closes(ruleFormRef)">取消</el-button>
                    </div>
                </div>
            </el-card>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { activeAdd, activeDel, scienList, ticketStatus, asst_add, ticlist, status_up, status_add, ticket_del } from '../../../api/active/index';
import { ElMessage, ElCard, ElDropdown } from 'element-plus';
import { Plus, Search, ArrowLeft, ArrowDown, RefreshRight } from '@element-plus/icons-vue';
import { inject } from 'vue'
import { status } from 'nprogress';
import { log } from 'console';

// 全局域名
const testFn = inject('testFn')
testFn()
const testName = inject('testName')
const dialogTableVisible = ref(false);
const statused = ref('');

// 数据变量
const activeList = ref([]);  // 门票列表数据
const activeStatu = ref(true)  // 控制显示列表页
const activeStatud = ref(false)  // 控制显示表单页

// 表格分页控制
const inputed = ref('');  // 搜索关键词
const pageSize = ref(5);  // 每页显示数量
const currentPage = ref(1);  // 当前页码
const copyList = ref([]);  // 数据副本，用于搜索过滤
const files = ref(false);

// 用户信息
let tokens = JSON.parse(localStorage.getItem('tokens'));
console.log(tokens);

// 编辑评分值
const value_f = ref()

// 状态筛选选项
const value = ref('')
const options = [
    { value: '1', label: '上架' },
    { value: '2', label: '下架' }
]

// 景区列表数据
const sceniclist = ref([])

// 初始化渲染数据
render();
function render() {
    // 获取门票列表
    ticlist({
        token: tokens.token,
        uid: tokens.userinfo.id
    }, {
        userid: tokens.userinfo.id
    }).then((res) => {
        console.log(res.data);
        activeList.value = res.data;
        copyList.value = res.data;
    });
    
    // 获取景区列表
    scienList({
        token: tokens.token,
        uid: tokens.userinfo.id
    }, {
        userid: tokens.userinfo.id
    }).then((res) => {
        console.log(res);
        sceniclist.value = res.data
    });
}

// 门票上下架状态切换
let statust = ref('');
function funstatus(e) {
    console.log(e);
    
    // 切换状态值
    if (e.state == '1') {
        statust.value = '2';  // 从上架变为下架
    } else if (e.state == '2') {
        statust.value = '1';  // 从下架变为上架
    }
    console.log(statust.value);
    
    // 调用API更新状态
    status_up(
        {
            token: tokens.token,
            uid: tokens.userinfo.id,
        },
        {
            userid: tokens.userinfo.id,
            id: e.id,
            state: statust.value
        }
    ).then((res) => {
        console.log(res);
        if (res.code == 1) {
            ElMessage({
                message: '操作成功',
                type: 'success',
            });
            render();  // 刷新数据
        } else if (res.code == 0) {
            ElMessage({
                message: res.msg,
                type: 'warning',
            });
        }
    });
}

// 表单数据对象
const ruleForm = reactive({
    name: '',  // 景区ID
    img: '',  // 图片
    title: '',  // 门票名称
    price: '',  // 门票价格
    jqdh: '',  // 景点电话
    yysj: '',  // 营业时间
    jqdz: '',  // 景点地址
    jd: '',  // 经度
    wd: '',  // 纬度
    dpdz: '',  // 店铺地址
    covers: '',  // 封面图
    introduce: '',  // 介绍
    synopsis: '',  // 简介
    switch: '1'  // 上下架状态
});

const stattess = ref('')
// switch开关事件，同步状态值
const funstate = () => {
    console.log(ruleForm.switch);
    if (ruleForm.switch == true) {
        stattess.value = '1'  // 上架
    } else if (ruleForm.switch == false) {
        stattess.value = '2'  // 下架
    }
}

// 表单引用和验证规则
const ruleFormRef = ref('');
const rules = reactive({
    synopsis: [
        {
            required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => {
                if (!value) {
                    callback(new Error('请输入门票简介'));
                } else if (value.length > 219) {
                    callback(new Error('仅最多输入220个字'));
                } else {
                    callback();
                }
            },
        },
    ],
    name: [
        {
            required: true,
            message: '请选择景区分类',
            trigger: 'blur',
        },
    ],
    title: [
        {
            required: true,
            message: '请输入门票名称',
            trigger: 'blur',
        },
    ],
    price: [
        {
            required: true,
            message: '请输入门票价格',
            trigger: 'blur',
        }
    ],
    jqdh: [
        {
            required: true,
            message: '请输入景点电话',
            trigger: 'blur',
        },
    ],
    img: [
        {
            required: true,
            message: '请上传轮播图片',
            trigger: 'change',
        },
    ],
    yysj: [
        {
            required: true,
            message: '请输入营业时间',
            trigger: 'change',
        },
    ],
});

// 时间验证函数
function validateEmailDomain(rule, value, callback) {
    if (value === '') {
        callback(new Error('结束时间不能为空'));
    } else if (value < ruleForm.start_time) {
        callback(new Error('结束时间不能小于开始时间'));
    } else {
        callback();
    }
}

// 提交表单（新增或编辑）
const submitForm = (formEl) => {
    if (!formEl) return;
    
    // 表单验证
    formEl.validate((valid) => {
        if (valid) {
            if (statused.value == '1') {
                // 新增门票
                const existingData = activeList.value.find(item => item.title === ruleForm.title);
                if (existingData) {
                    console.log('数据已存在，无法新增');
                    ElMessage({
                        message: '当前门票已存在',
                        type: 'warning',
                    })
                    return false;
                } else {
                    // 调用新增API
                    status_add({ token: tokens.token, uid: tokens.userinfo.id }, {
                        userid: tokens.userinfo.id,
                        title: ruleForm.title,
                        scenicid: ruleForm.name,
                        intr: ruleForm.synopsis,
                        price: ruleForm.price,
                        sold: 1,
                        state: stattess.value
                    }).then((res) => {
                        console.log(res);

                        if (res.code == '1') {
                            ElMessage({
                                message: '新增成功',
                                type: 'success',
                            });
                            setTimeout(() => {
                                activeStatud.value = false;  // 隐藏表单页
                                activeStatu.value = true;  // 显示列表页
                                ruleForm.switch = false
                            }, 1200);

                            render();  // 刷新数据
                        } else {
                            // 处理错误
                        }
                    });
                }
            } else if (statused.value == '2') {
                // 编辑门票
                console.log(ruleForm);
                
                // 调用编辑API
                status_add({ token: tokens.token, uid: tokens.userinfo.id }, {
                    userid: tokens.userinfo.id,
                    id: ids.value,
                    title: ruleForm.title,
                    scenicid: ruleForm.name,
                    intr: ruleForm.synopsis,
                    price: ruleForm.price,
                    sold: 1,
                    state: stattess.value
                }).then((res) => {
                    if (res.code == '1') {
                        ElMessage({
                            message: '编辑成功',
                            type: 'success',
                        });
                        setTimeout(() => {
                            activeStatud.value = false;  // 隐藏表单页
                            activeStatu.value = true;  // 显示列表页
                            // 重置表单
                            ruleForm.title = ''
                            ruleForm.name = ''
                            ruleForm.synopsis = ''
                            ruleForm.name = ''
                            ruleForm.price = ''
                            ruleForm.switch = false
                        }, 1200);

                        render();  // 刷新数据
                    } else {
                        ElMessage({
                            message: '编辑失败，不能和原数据一致',
                            type: 'warning',
                        });
                    }
                });
            }
        }
        else {
            ElMessage({
                message: '编辑失败',
                type: 'error',
            });
        }
    });
};

// 编辑用的ID
const ids = ref('');
const disableds = ref(true);

// 关闭新增/编辑表单
const closes = (formEl) => {
    console.log(formEl);
    activeStatu.value = true  // 显示列表页
    activeStatud.value = false  // 隐藏表单页
    formEl.resetFields();  // 重置表单
    formEl.clearValidate()  // 清除验证
    dialogTableVisible.value = false;
    files.value = false;
    ruleForm.name = ''
    ruleForm.switch = false
};

const title = ref('')  // 表单标题

// 点击新增按钮
const add = () => {
    activeStatud.value = true  // 显示表单页
    activeStatu.value = false  // 隐藏列表页
    title.value = '添加'  // 设置标题
    statused.value = '1';  // 标记为新增操作
}

// 点击编辑按钮
function edit(item) {
    console.log(item);
    title.value = '编辑'  // 设置标题
    
    // 同步状态值
    stattess.value = item.state
    if (item.state == 1) {
        ruleForm.switch = true
    } else {
        ruleForm.switch = false
    }
    
    // 保存编辑ID和填充表单数据
    ids.value = item.id;
    activeStatud.value = true  // 显示表单页
    activeStatu.value = false  // 隐藏列表页
    ruleForm.name = item.scenicid
    ruleForm.price = item.price
    ruleForm.title = item.title
    ruleForm.synopsis = item.intr
    disableds.value = false;
    statused.value = '2';  // 标记为编辑操作
}

// 点击删除按钮
function deletes(item) {
    console.log(item);
    centerDialogVisible.value = true;  // 显示删除确认弹窗
    deleteids.value = item.id;  // 保存要删除的ID
}

const deleteids = ref('');
const centerDialogVisible = ref(false);

// 确认删除
function deleteid() {
    // 调用删除API
    ticket_del(
        {
            token: tokens.token,
            uid: tokens.userinfo.id,
        },
        {
            userid: tokens.userinfo.id,
            id: deleteids.value,
        }
    ).then((res) => {
        if (res.code == '1') {
            centerDialogVisible.value = false;  // 关闭确认弹窗
            ElMessage({
                message: '删除成功',
                type: 'success',
            });
            render();  // 刷新数据
        }
    });
}

// 分类名称搜索
function filters() {
    currentPage.value = 1  // 重置页码
    console.log(inputed.value);
    
    // 过滤数据
    activeList.value = copyList.value.filter(function (item) {
        // 判断是否满足搜索条件
        if (String(item.title).indexOf(String(inputed.value)) > -1) {
            return item;
        }
    });
    
    currentPage.value = 1  // 重置页码
}

// 上下架搜索
const ange_indexof = (e) => {
    console.log(e);
    if (e == undefined) {
        render()  // 如果没有选择筛选条件，则刷新数据
    }
    
    // 过滤数据
    activeList.value = copyList.value.filter(function (item) {
        // 判断是否满足搜索条件
        if (String(item.state).indexOf(String(e)) > -1) {
            return item;
        }
    });
    
    currentPage.value = 1  // 重置页码
}

const shows = ref(false);

// 批量删除相关
const SelectArr = ref([])  // 选中的行数据
const All_Delete = ref([])  // 选中的ID数组

// 表格选择变化事件
const handleSelectionChange = (val) => {
    All_Delete.value = []
    SelectArr.value = val
    
    // 收集选中的ID
    SelectArr.value.forEach(item => {
        console.log(item);
        All_Delete.value.push(item.id)
    })
    console.log(All_Delete.value);
}

// 批量删除
const centerDialogVisiblet = ref(false)
const st = ref([])
function deleList() {
    st.value = []
    console.log(All_Delete.value);
    st.value.push(All_Delete.value)
    
    // 检查是否有选中项
    if (All_Delete.value == '') {
        ElMessage({
            message: '请勾选要删除的门票',
            type: 'warning',
        })
    } else {
        centerDialogVisiblet.value = true  // 显示批量删除确认弹窗
    }
}

// 确认批量删除
const deleteid_t = () => {
    // 调用批量删除API
    ticket_del({
        token: tokens.token,
        uid: tokens.userinfo.id
    }, {
        userid: tokens.userinfo.id,
        id: st.value.join(','),
    }).then(res => {
        console.log(res, '删除成功或失败回调');
        centerDialogVisiblet.value = false;  // 关闭确认弹窗
        render();  // 刷新数据
        ElMessage({
            message: '删除成功',
            type: 'success',
        })
    })
}

// 价格输入控制 - 减少
const decreaseQuantity = () => {
    if (ruleForm.price && parseInt(ruleForm.price) > 1) {
        ruleForm.price = (parseInt(ruleForm.price) - 1).toString();
    }
};

// 价格输入控制 - 增加
const increaseQuantity = () => {
    if (ruleForm.price) {
        ruleForm.price = (parseInt(ruleForm.price) + 1).toString();
    } else {
        ruleForm.price = '1';
    }
};

// 价格验证函数
const validateQuantity = (rule, value, callback) => {
    // 定义正整数正则表达式（不允许前导零）
    const reg = /^[1-9]\d*$/;

    if (!value) {
        callback(new Error('请输入浏览量'));
    } else if (!reg.test(value)) {
        callback(new Error('请输入大于0的正整数'));
    } else {
        callback();
    }
};

// 处理输入事件，过滤非数字字符
const handleQuantityInput = (event) => {
    // 获取输入值
    let value = event.target.value;

    // 过滤非数字字符
    value = value.replace(/[^0-9]/g, '');

    // 不允许前导零（除非是单个0，但我们的规则是大于0的正整数）
    if (value.startsWith('0') && value.length > 1) {
        value = value.substring(1);
    }

    // 更新Vue数据
    ruleForm.price = value;
};

// 处理失焦事件，验证输入
const validateQuantityInput = () => {
    const value = ruleForm.price;
    const reg = /^[1-9]\d*$/;

    if (value && !reg.test(value)) {
        ElMessage({
            type: 'warning',
            message: '请输入大于0的正整数'
        });
        // 清空无效输入
        ruleForm.price = '';
    }
};
</script>

<style>
/* 引入高德地图样式 */
@import url("https://cache.amap.com/lbs/static/main1119.css");

.text {
    font-size: 14px;
}

.item {
    margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
    display: table;
    content: '';
}

.clearfix:after {
    clear: both;
}

.box-card {
    display: flex;
    height: 300px;
    width: 90%;
}

.handle {
    display: flex;
    align-items: center;
    justify-content: center;
}

.paging {
    display: flex;
    justify-content: center;
    margin-top: 10px;
    height: 70px;
}

.flex {
    display: flex;
    align-items: center;
    padding-bottom: 10px;
}

.flexBox {
    display: flex;
    width: 100%;
    align-items: center;
}

/* 自定义数字输入框样式 */
.custom-number-input {
    display: flex;
    align-items: center;
    width: 120px;
}

.custom-number-input button {
    width: 53px;
    height: 38px;
    border: 1px solid #dcdfe6;
    background-color: #f5f7fa;
    color: #606266;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    user-select: none;
}

.custom-number-input button:hover {
    background-color: #e4e7ed;
}

.custom-number-input button:first-child {
    border-radius: 4px 0 0 4px;
}

.custom-number-input button:last-child {
    border-radius: 0 4px 4px 0;
}

.custom-number-input input {
    flex: 1;
    height: 38px;
    border: 1px solid #dcdfe6;
    border-left: none;
    border-right: none;
    text-align: center;
    padding: 0 5px;
    font-size: 14px;
    outline: none;
    width: 80px;
}

.custom-number-input input:focus {
    border-color: #409eff;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}
</style>